package com.jiang.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiang.dto.Result;
import com.jiang.dto.ScrollResult;
import com.jiang.dto.UserDTO;
import com.jiang.entity.Blog;
import com.jiang.entity.Follow;
import com.jiang.entity.User;
import com.jiang.mapper.BlogMapper;
import com.jiang.service.IBlogService;
import com.jiang.service.IFollowService;
import com.jiang.service.IUserService;
import com.jiang.utils.SystemConstants;
import com.jiang.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.jiang.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.jiang.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiang
 * @since 2024-3-20
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            queryBlogUser(blog);
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        // 1、查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("博客不存在！");
        }
        // 2、查询blog有关的用户
        queryBlogUser(blog);
        // 3、查询blog是否被点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO userDTO = UserHolder.getUser();
        // 判断是否登录
        if (userDTO == null) {
            return;
        }
        // 1、 获取当前用户
        Long userId = userDTO.getId();
        // 2、判断当前登录用户是否已经点赞
        Long id = blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + id, userId.toString());
        blog.setIsLike(score != null);
    }

    @Override
    public Result likeBlog(Long id) {
        // 1、 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2、判断当前登录用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + id, userId.toString());
        // 3、如果未点赞，可以点赞
        if (score == null) {
            // 3.1 数据库点赞树 + 1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            // 3.2 保存用户到redis的set集合
            if (isSuccess) {
                // 保存该评论点赞用户的 id 和 点赞时间
                stringRedisTemplate.opsForZSet().add(BLOG_LIKED_KEY + id, userId.toString(), System.currentTimeMillis());
            }
        } else {
            // 4、如果已点赞，取消点赞
            // 4.1 数据库点赞树 - 1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            // 4.2 删除用户从redis的set集合
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(BLOG_LIKED_KEY + id, userId.toString());
            }
        }

        return Result.ok();
    }

    @Override
    public Result queryBlogByLikes(Long id) {
        // 1、查询top5点赞用户 zrange key 0 4
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(BLOG_LIKED_KEY + id, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        // 2、 解析出其中的用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        // 3、根据用户id查询用户 使用listByIds()后底层执行 WHERE id IN (5， 1)， in 结果会默认按id大小排序， 导致id大的如果先点赞就一直在后面， 解决方法用  order by filed (id, 1, 5)。  last 就是对query语句进行拼接
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids)
                .last("order by field(id," + StrUtil.join(",", ids) + ")")
                .list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 4、返回
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 1、获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 2、保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            return Result.fail("新增笔记失败！");
        }
        // 3、查询笔记作者的所有粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        // 4、推送笔记id给所有粉丝
        for (Follow follow : follows) {
            // 4.1 获取粉丝id
            Long userId = follow.getUserId();
            // 4.2 推送
            String key = FEED_KEY + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 5、返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 1、获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2、查询收件箱
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        // 3、解析数据： blogId、minTime（时间戳）、offset
        List<Long> blogIds = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            // 3.1 获取blogId
            blogIds.add(Long.valueOf(Objects.requireNonNull(typedTuple.getValue())));
            // 3.2 获取时间戳
            long time = Objects.requireNonNull(typedTuple.getScore()).longValue();
            if (minTime == time) {
                os++;
            } else {
                minTime = time;
                os = 1;
            }
        }
        // 解决多线程重复查询的问题 minTime：这一次最小score值， max：上一次最小score值
        os = minTime != max ? os : os + offset;
        // 4、根据blogId查询blog
        String idStr = StrUtil.join(",", blogIds);
        List<Blog> blogs = query()
                .in("id", blogIds)
                .last("order by field(id," + idStr + ")")
                .list();
        for (Blog blog : blogs) {
            // 4.1、查询blog有关的用户
            queryBlogUser(blog);
            // 4.2、查询blog是否被点赞
            isBlogLiked(blog);
        }
        // 5、封装并返回
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setOffset(os);
        r.setMinTime(minTime);
        return Result.ok(r);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
